<?php
/**
 * Created by PhpStorm.
 * User: renyi
 * Date: 2017/10/13
 * Time: 上午3:24
 */

namespace App\Core;


use App\Misc\ArrayToolkit;

trait BaseServiceMethod
{
    protected $model;
    protected $available_create_fields = [];
    protected $available_search_fields = [];

    public function intelli_add($search_fields, $added_fields = [], $need_update = true)
    {
        // 获得最近的
        $object = $this->search_one($search_fields);

        // 增加added
        $union_fields = array_merge($search_fields, $added_fields);

        // 如果没有则新建
        if (empty($object))
        {
            // 添加
            $object = $this->add($union_fields);
        }
        else
        {
            if ($need_update)
            {
                // 更新
                $this->update($object->id, $union_fields);
            }
        }

        return $object;
    }

    public function add($fields)
    {
        $save_item = [];

        foreach ($this->available_create_fields as $target)
        {
            $value = ArrayToolkit::get($fields, $target);

            if ($value !== NULL)
            {
                $save_item[$target] = $value;
            }
        }

        // 生成
        $object = $this->model::create($save_item);

        return $object;
    }

    /**
     * 获得一个
     *
     * @param $fields
     * @return mixed
     */
    public function search_one($fields)
    {
        return $this->search($fields)->first();
    }

    /**
     * 获得所有
     *
     * @param $fields
     * @return mixed
     */
    public function search_all($fields)
    {
        return $this->search($fields)->get();
    }

    /**
     * 获得一个
     *
     * @param $fields
     * @return mixed
     */
    public function search_count($fields)
    {
        return $this->search($fields)->count();
    }

    /**
     * 搜索
     *
     * @param $fields
     * @return mixed
     */
    public function search($fields)
    {
        // 生成搜索条件
        $search_condition = [];

        foreach ($this->available_search_fields as $target)
        {
            $value = ArrayToolkit::get($fields, $target);

            if ($value !== NULL && $value !== "")
            {
                $search_condition[$target] = $value;
            }
        }

        return $this->model::where($search_condition)->orderBy('id', 'desc');
    }

    /**
     * 更新
     *
     * @param $id
     * @param $fields
     * @return mixed
     */
    public function update($id, $fields)
    {
        return $this->model::where('id', $id)->update($fields);
    }

    /**
     * 删除
     *
     * @param $id
     */
    public function delete($id)
    {
        $this->model::destroy($id);
    }
}